package com.koron.css2.serviceManage.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.baseConfig.bean.PubReceiptBean;
import com.koron.css2.baseConfig.mapper.PubReceiptMapper;
import com.koron.css2.serviceManage.bean.ProcessNodeBean;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.css2.workflow.WorkflowImpl;
import com.koron.util.Constant;
import com.koron.util.DBSourceUtils;
import org.bson.types.ObjectId;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 流程结点信息刷新
 * @author admin
 *
 */
public class ProcessConfigNodeRefresh implements ServerInterface {

	@Override
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {

		@SuppressWarnings("rawtypes")
		MessageBean<List> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", List.class);
		try {
			Map<?,?> map = JsonUtils.objectToPojo(req.getData(), HashMap.class);
			if(map.get("processCode") == null) {
				return MessageBean.create(Constant.MESSAGE_DBFAIL, "processCode 参数不能为空", Void.class);
			}
			String processCode = map.get("processCode") + "";
			String companyNo = map.get("companyNo") + "";
			//读取对应水司的流程平台应用密钥
			PubReceiptMapper mapper = factory.getMapper(PubReceiptMapper.class);
			String setCode = mapper.getWorkflowApp(companyNo);
			//查询流程配置信息 
			PubReceiptBean receipt = mapper.selectByProcessCode(processCode);
			//调用接口取流程节点信息
			List<ProcessNodeBean> data = WorkflowImpl.getWorkflowDefine(setCode, receipt.getProcessCode());
			
			PubReceiptMapper baseMapper = factory.getMapper(PubReceiptMapper.class, DBSourceUtils.getDbEnv(companyNo));
			//删除所有原结点信息
			baseMapper.deleteProcessNode(receipt.getReceiptNo());
			//插入新的结点信息
			for(ProcessNodeBean bean : data) {
				bean.setProcessId(receipt.getReceiptId());
				bean.setProcessNodeId(new ObjectId().toHexString());
				bean.setReceiptType(receipt.getReceiptNo());
				baseMapper.insertProcessNode(bean);
			}
		} catch (Exception e) {
			info.setCode(Constant.MESSAGE_INT_FAIL);
			info.setDescription(e.getMessage());
			logger.error(e.getMessage(), e);
		}
		return info;
	}
}
